import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 15000
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code !== 20000) {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

const requestApi = (opts, params) => {
	//拦截区    
	let promise = new Promise((resolve, reject) => {
		service({
			url: opts.url ,
			method: opts.method || 'post',
			header: {},
			data: {  
        ...params,
        token: getToken()
			},
			success(res) {
				resolve(res.data); 
			},
			fail(err) {
				reject(err);
			},
			complete() {
			}
		});
	});
	return promise;
};

export default requestApi
